import { Logger as NestLogger } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { ConfigService } from '@nestjs/config';
import { AppModule } from './app.module';

async function bootstrap(): Promise<string> {
  // 创建 NestJS 应用实例
  const app = await NestFactory.create(AppModule);

  // 获取配置服务
  const config = app.get(ConfigService);
  const prefix = config.get<string>('API_PREFIX');

  if (!prefix) {
    throw new Error('API_PREFIX is not defined');
  }

  // 全局接口前缀
  app.setGlobalPrefix(prefix);

  // 配置 Swagger 文档选项
  const options = new DocumentBuilder()
    .setTitle('OpenAPI Documentation')
    .setDescription('The sample API description')
    .setVersion('1.0')
    .addBearerAuth() // 添加 Bearer 认证支持
    .build();

  // 创建 Swagger 文档
  const document = SwaggerModule.createDocument(app, options);

  // 设置 Swagger UI 访问路径
  SwaggerModule.setup('api', app, document);

  // 启动应用
  await app.listen(process.env.PORT || 8000);

  return await app.getUrl();
}

// 自执行异步函数启动应用
void (async (): Promise<void> => {
  try {
    const url = await bootstrap();
    NestLogger.log(url + '/api', 'Bootstrap Swagger URL');
  } catch (error) {
    NestLogger.error(error, 'Bootstrap');
  }
})();